var itembox = document.querySelector('.itembox')
let arr = []
page(localStorage.getItem('current') || 1)
function page(n) {
  itembox.innerHTML = ''
  pAjax({
    url: '../server/list.php',
    type: 'get',
    data: {
      pagenum: n,
      pagesize: 12
    }
  }).then(function (res) {
     arr = JSON.parse(res)
    arr.forEach(ele => {
      let str = `
        <li class="spitem">
              <div class="spimg">
                <a href="../html/details.html?id=${ele.goods_id}" target="_blank"><img src="${ele.goods_big_logo}" alt=""></a>
              </div>
              <a href="../html/details.html?id=${ele.goods_id}" target="_blank"><h6>${ele.goods_name}</h6></a>
              <p><span>￥${ele.goods_price}</span>暂无评论</p>
              <s>￥${ele.goods_price}</s>
              <div class="buy">
                <div class="count">
                  <div class="sub">-</div>
                  <input type="text" value="1">
                  <div class="sum">+</div>
                </div>
                <div class="addcart" data-id="${ele.goods_id}">加入购物车</div>
              </div>
              <div class="spbtn">
                <button>收藏</button>
                <button>对比</button>
              </div>
            </li>
        `
      itembox.innerHTML += str
    })


  })
}

$('.M-box1').pagination({
  current: parseInt(localStorage.getItem('current')) || 1,
  totalData: 922,
  showData: 12,
  coping: true,
  keepShowPN: true,
  count: 2,
  callback(index) {
    localStorage.setItem('current', index.getCurrent())
    page(index.getCurrent())
  }
});


itembox.addEventListener('click',function(e){
  e = e || window.event
  var target = e.target || e.srcElement
 if(target.className=='addcart'){
  let num = target.parentNode.querySelector('input').value
  let id = e.target.getAttribute('data-id')
  let carArr = JSON.parse(localStorage.getItem('shopArr'))||[]
        // 是否找到商品
        let flag = true
        // 去重
        carArr.forEach(ele => {
            if (ele.goods_id === id) {
                ele.count+=parseInt(num)
                flag = false
            }
        })

        // 存一个商品对象值
        if (flag) {
            arr.forEach(ele => {
                if (ele.goods_id === id) {
                  carArr.push({
                        count: parseInt(num),
                        flag: true,
                        ...ele
                    })
                }
            })
        }

        // console.log(newArr)
        // 存到购物车列表页
        localStorage.setItem('shopArr', JSON.stringify(carArr))
        alert('成功加入购物车')
 }
 if(target.className=='sub'){
  if(target.nextElementSibling.value>1){
    target.nextElementSibling.value--
  }else{
    target.nextElementSibling.value=1
  }
 }
 if(target.className=='sum'){
    target.previousElementSibling.value++
 }
})
